<template>
  <el-dialog v-model="dialogFormVisible" :title="cate.id ? '编辑分类' : '新增分类'" width="500">
    <el-form :model="cate" :rules="rules" ref="form">
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="cate.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="cate.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { addCate, updateCate } from '@/api/cate';
import type { Cate } from '@/types';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
const dialogFormVisible = ref(false)
const getInit = (): Cate => {
  return {
    cate_alias: "",
    cate_name: "",
    id: undefined,
  }
}
const cate = ref<Cate>(getInit())

const cancel = () => {
  cate.value = getInit()
  dialogFormVisible.value = false
}
const form = ref()
const confirm = async () => {
  //验证参数
  await form.value.validate()
  //保存or新增
  if (cate.value.id) {
    updateCate(cate.value)
    ElMessage.success('编辑成功')
  } else {
    ElMessage.success('新增成功')
    addCate(cate.value)
  }
  dialogFormVisible.value = false
  cate.value = getInit()
  $success("success")

}


const rules = {
  cate_name: [
    { required: true, message: '请输入名称', trigger: 'blue' }
  ],
  cate_alias: [
    { required: true, message: '请输入别名', trigger: 'blue' },
    {
      pattern: /^[A-Za-z0-9]+$/, message: '别名只能包含字母和数字', trigger: 'blur'
    }
  ]
}
const open = (row?: Cate) => {
  dialogFormVisible.value = true
  if (row) {
    cate.value = { ...row }
  }
}
defineExpose({
  open
})

const $success = defineEmits(['success']);
</script>

<style scoped></style>
